package uploader

import (
	"bytes"
	"client/common/response"
	file2 "client/file"
	"client/services"
	"client/utils"
	"context"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

type DirectUploader struct {
	FilePath string // 待上传文件路径
	client   http.Client
}

func (u *DirectUploader) Upload(c context.Context) {
	_, err := utils.FileExist(u.FilePath)
	if err != nil {
		fmt.Println(err)
		return
	}

	var file *os.File
	file, err = os.OpenFile(u.FilePath, os.O_RDONLY, 0666)
	if err != nil {
		fmt.Println(err)
		return
	}

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	var part io.Writer
	part, err = writer.CreateFormFile("file", file.Name())
	if err != nil {
		fmt.Println(err)
		return
	}

	_, err = io.Copy(part, file)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = writer.Close()
	if err != nil {
		fmt.Println(err)
		return
	}

	var req *http.Request
	req, err = http.NewRequestWithContext(c, http.MethodPost, services.UploadApiInstance.DirectUpload, body)
	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())
	var res *http.Response
	res, err = u.client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}

	var resp *response.Response
	resp, err = response.ParseResponse(res)
	if err != nil {
		fmt.Println(err)
		return
	}
	var fileMeta *file2.FileMeta
	fileMeta, err = resp.GetRespFileMeta()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("upload success, filename: %s, fid: %s\n", fileMeta.Name, fileMeta.Fid)

	defer func() {
		_ = writer.Close()
		_ = file.Close()
	}()
}

func NewDirectUploader(path string, client http.Client) *DirectUploader {
	return &DirectUploader{
		client:   client,
		FilePath: path,
	}
}
